import { Game } from '../core/Game';
import { BilliardGame } from '../game/BilliardGame';
import { SendWebSocket } from '../websocket/SendWebSocket';
import { NetKeyFrame } from '../core/WebSocketData';

export class WebFrameCollection {
  // 最近一次收集数据的时间戳
  private latestTimestamp = 0;
  // 记录每一步白球击球 的帧列表
  private keyFrameList: Array<NetKeyFrame> = [];
  private sendIndex = 0;
  
  constructor() { }
  public startGame() {
    this.latestTimestamp = 0;
    this.sendIndex = 0;
    this.keyFrameList.length = 0;
  }
  // 初始化开始
  public startCollectFrame() {
    this.latestTimestamp = 0;
    this.sendIndex = 0;
    this.keyFrameList.length = 0;
  }
  // 结束
  public endCollectFrame() {
  }
  // 收集当前帧数据，并发送
  public collectSendFrame(deltaTime: number) {
    if (BilliardGame.Instance().actionStage.isSyncFrameStage()) {
      const tt = Date.now() - BilliardGame.Instance().currentTimestamp;
      if (tt > this.latestTimestamp + 60) {
        this.latestTimestamp = tt;
        const frame = this.collectFrame(0);
        this.keyFrameList.push(frame);
      }
    }
    
    if (this.sendIndex >= 0 && this.sendIndex < this.keyFrameList.length) {
      new SendWebSocket().sendKeyFrame(this.keyFrameList[this.sendIndex]);
      this.sendIndex += 1;
    }
  }
  public collectFirstFrame() {
    return this.collectFrame(0);
  }
  public collectCurrentFrame() {
    return this.collectFrame(0);
  }
  public collectEndFrame() {
    return this.collectFrame(1);
  }
  private collectFrame(flag: number) {
    const balls = BilliardGame.Instance().getAllBallList();
    return new NetKeyFrame(
      Game.Instance().currentStep,
      BilliardGame.Instance().currentFrameSeq,
      Date.now() - BilliardGame.Instance().currentTimestamp,
      flag, balls
    );
  }
}

